<template>
  <div class="dashboard-container">
    <div class="dashboard-header">
      <h2 class="page-title">系统仪表板</h2>
      <p class="page-description">欢迎使用服务器迁移管理系统，这里展示了系统的整体运行状态</p>
    </div>
    
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-grid">
      <el-col :xs="12" :sm="6" :lg="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon" :style="{ backgroundColor: '#409EFF20', color: '#409EFF' }">
              <i class="el-icon-monitor"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ (serverStats && serverStats.total) || 0 }}</div>
              <div class="stat-label">服务器数量</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="12" :sm="6" :lg="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon" :style="{ backgroundColor: '#67C23A20', color: '#67C23A' }">
              <i class="el-icon-circle-check"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ (serverStats && serverStats.online) || 0 }}</div>
              <div class="stat-label">在线服务器</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="12" :sm="6" :lg="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon" :style="{ backgroundColor: '#E6A23C20', color: '#E6A23C' }">
              <i class="el-icon-position"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ (taskStats && taskStats.total) || 0 }}</div>
              <div class="stat-label">迁移任务</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="12" :sm="6" :lg="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon" :style="{ backgroundColor: '#F56C6C20', color: '#F56C6C' }">
              <i class="el-icon-warning-outline"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ (taskStats && taskStats.running) || 0 }}</div>
              <div class="stat-label">运行中任务</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 用户统计卡片 -->
    <el-row :gutter="20" class="stats-grid">
      <el-col :xs="12" :sm="6" :lg="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon" :style="{ backgroundColor: '#90939920', color: '#909399' }">
              <i class="el-icon-user"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ (userStats && userStats.totalUsers) || 0 }}</div>
              <div class="stat-label">总用户数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="12" :sm="6" :lg="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon" :style="{ backgroundColor: '#67C23A20', color: '#67C23A' }">
              <i class="el-icon-user-solid"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ (userStats && userStats.onlineUsers) || 0 }}</div>
              <div class="stat-label">在线用户</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="12" :sm="6" :lg="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon" :style="{ backgroundColor: '#E6A23C20', color: '#E6A23C' }">
              <i class="el-icon-circle-plus"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ (userStats && userStats.newUsers) || 0 }}</div>
              <div class="stat-label">新增用户</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="12" :sm="6" :lg="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon" :style="{ backgroundColor: '#409EFF20', color: '#409EFF' }">
              <i class="el-icon-document"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ (logs || []).length }}</div>
              <div class="stat-label">操作日志</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 图表区域 -->
    <el-row :gutter="20" class="charts-row">
      <el-col :xs="24" :lg="12">
        <el-card class="chart-card" shadow="hover">
          <div slot="header" class="card-header">
            <span>迁移任务状态统计</span>
            <el-button type="text" @click="goToMigrations">查看更多</el-button>
          </div>
          <div class="chart-container">
            <div ref="statusChart" class="chart-placeholder"></div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :lg="12">
        <el-card class="chart-card" shadow="hover">
          <div slot="header" class="card-header">
            <span>服务器操作系统分布</span>
            <el-button type="text" @click="goToServers">查看更多</el-button>
          </div>
          <div class="chart-container">
            <div ref="osChart" class="chart-placeholder"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 最近活动 -->
    <el-card class="recent-activity" shadow="hover">
      <div slot="header" class="card-header">
        <span>最近活动</span>
        <el-button type="text" @click="goToLogs">查看更多</el-button>
      </div>
      <div class="activity-list">
        <div class="activity-item" v-for="activity in recentActivities" :key="activity.id">
          <div class="activity-icon" :style="{ backgroundColor: getActivityColor(activity.type) + '20', color: getActivityColor(activity.type) }">
            <i :class="getActivityIcon(activity.type)"></i>
          </div>
          <div class="activity-content">
            <div class="activity-title">{{ activity.title }}</div>
            <div class="activity-description">{{ activity.description }}</div>
            <div class="activity-time">{{ activity.time }}</div>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
import * as echarts from 'echarts'
import moment from 'moment'

export default {
  name: 'Dashboard',
  data() {
    return {
      serverStats: {
        total: 0,
        online: 0,
        offline: 0,
        error: 0
      },
      taskStats: {
        total: 0,
        running: 0,
        completed: 0,
        failed: 0
      },
      userStats: {
        totalUsers: 0,
        onlineUsers: 0,
        newUsers: 0
      },
      logs: [],
      recentActivities: [
        {
          id: 1,
          type: 'migration',
          title: '新迁移任务创建',
          description: '用户admin创建了新的服务器迁移任务',
          time: '5分钟前'
        },
        {
          id: 2,
          type: 'server',
          title: '服务器添加',
          description: '添加了新的Linux服务器',
          time: '1小时前'
        },
        {
          id: 3,
          type: 'login',
          title: '用户登录',
          description: '用户admin成功登录系统',
          time: '2小时前'
        },
        {
          id: 4,
          type: 'migration',
          title: '迁移任务完成',
          description: '服务器迁移任务已完成',
          time: '3小时前'
        }
      ],
      statusChart: null,
      osChart: null,
      chartInstances: []
    }
  },
  computed: {
    // 重新定义计算属性，避免与data中的属性冲突
    serverList() {
      return this.$store.state.server.servers || []
    },
    taskList() {
      return this.$store.state.migration.tasks || []
    },
    userStatsFromStore() {
      return this.$store.state.users.stats || null
    },
    allLogsFromStore() {
      return this.$store.state.logs.allLogs || []
    }
  },
  async created() {
    await this.loadDashboardData()
  },
  mounted() {
    this.initCharts()
    window.addEventListener('resize', this.handleResize)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize)
    this.chartInstances.forEach(chart => {
      if (chart) {
        chart.dispose()
      }
    })
  },
  methods: {
    ...mapActions('server', ['fetchServers']),
    ...mapActions('migration', ['fetchTasks']),
    ...mapActions('users', ['fetchUserStats']),
    ...mapActions('logs', ['fetchLogs']),
    async loadDashboardData() {
      try {
        // 并行加载所有数据
        await Promise.all([
          this.fetchServers(),
          this.fetchTasks(),
          this.fetchUserStats(),
          this.fetchLogs()
        ])
        
        // 处理服务器数据
        this.serverStats.total = this.serverList ? this.serverList.length : 0
        this.serverStats.online = this.serverList ? this.serverList.filter(s => s.status === 'ONLINE').length : 0
        this.serverStats.offline = this.serverList ? this.serverList.filter(s => s.status === 'OFFLINE').length : 0
        this.serverStats.error = this.serverList ? this.serverList.filter(s => s.status === 'ERROR').length : 0
        
        // 处理任务数据
        this.taskStats.total = this.taskList ? this.taskList.length : 0
        this.taskStats.running = this.taskList ? this.taskList.filter(t => t.status === 'RUNNING').length : 0
        this.taskStats.completed = this.taskList ? this.taskList.filter(t => t.status === 'COMPLETED').length : 0
        this.taskStats.failed = this.taskList ? this.taskList.filter(t => t.status === 'FAILED').length : 0
        
        // 处理用户统计数据
        if (this.userStatsFromStore) {
          this.userStats.totalUsers = this.userStatsFromStore.totalUsers || 0
          this.userStats.onlineUsers = this.userStatsFromStore.onlineUsers || 0
          this.userStats.newUsers = this.userStatsFromStore.newUsers || 0
        }
        
        // 处理日志数据
        this.logs = this.allLogsFromStore || []
        
        // 初始化图表
        this.$nextTick(() => {
          this.initCharts()
        })
      } catch (error) {
        console.error('加载仪表盘数据失败:', error)
        this.$message.error('加载仪表盘数据失败: ' + error.message)
      }
    },
    initCharts() {
      // 销毁现有的图表实例
      this.chartInstances.forEach(chart => {
        if (chart) {
          chart.dispose()
        }
      })
      this.chartInstances = []
      
      // 初始化任务状态图表
      if (this.$refs.statusChart) {
        this.statusChart = echarts.init(this.$refs.statusChart)
        this.chartInstances.push(this.statusChart)
        
        this.statusChart.setOption({
          tooltip: {
            trigger: 'item'
          },
          legend: {
            bottom: '0%',
            left: 'center'
          },
          series: [
            {
              name: '任务状态',
              type: 'pie',
              radius: ['40%', '70%'],
              avoidLabelOverlap: false,
              itemStyle: {
                borderRadius: 10,
                borderColor: '#fff',
                borderWidth: 2
              },
              label: {
                show: false,
                position: 'center'
              },
              emphasis: {
                label: {
                  show: true,
                  fontSize: '18',
                  fontWeight: 'bold'
                }
              },
              labelLine: {
                show: false
              },
              data: [
                { value: this.taskStats.completed, name: '已完成', itemStyle: { color: '#67C23A' } },
                { value: this.taskStats.running, name: '运行中', itemStyle: { color: '#409EFF' } },
                { value: this.taskStats.failed, name: '失败', itemStyle: { color: '#F56C6C' } }
              ]
            }
          ]
        })
      }
      
      // 初始化操作系统分布图表
      if (this.$refs.osChart) {
        this.osChart = echarts.init(this.$refs.osChart)
        this.chartInstances.push(this.osChart)
        
        // 计算操作系统分布
        const osStats = {}
        if (this.serverList) {
          this.serverList.forEach(server => {
            const os = server.os || '未知'
            osStats[os] = (osStats[os] || 0) + 1
          })
        }
        
        const osData = Object.keys(osStats).map(os => ({
          name: os,
          value: osStats[os]
        }))
        
        this.osChart.setOption({
          tooltip: {
            trigger: 'item'
          },
          legend: {
            bottom: '0%',
            left: 'center'
          },
          series: [
            {
              name: '操作系统',
              type: 'pie',
              radius: ['40%', '70%'],
              avoidLabelOverlap: false,
              itemStyle: {
                borderRadius: 10,
                borderColor: '#fff',
                borderWidth: 2
              },
              label: {
                show: false,
                position: 'center'
              },
              emphasis: {
                label: {
                  show: true,
                  fontSize: '18',
                  fontWeight: 'bold'
                }
              },
              labelLine: {
                show: false
              },
              data: osData
            }
          ]
        })
      }
    },
    handleResize() {
      this.chartInstances.forEach(chart => {
        if (chart) {
          chart.resize()
        }
      })
    },
    goToMigrations() {
      this.$router.push('/migrations')
    },
    goToServers() {
      this.$router.push('/servers')
    },
    goToLogs() {
      this.$router.push('/logs')
    },
    getActivityIcon(type) {
      const iconMap = {
        'migration': 'el-icon-position',
        'server': 'el-icon-monitor',
        'login': 'el-icon-user',
        'backup': 'el-icon-document'
      }
      return iconMap[type] || 'el-icon-info'
    },
    getActivityColor(type) {
      const colorMap = {
        'migration': '#409EFF',
        'server': '#67C23A',
        'login': '#909399',
        'backup': '#E6A23C'
      }
      return colorMap[type] || '#409EFF'
    },
    formatDateTime(datetime) {
      return datetime ? moment(datetime).format('YYYY-MM-DD HH:mm:ss') : ''
    }
  }
}

<style lang="scss" scoped>
.dashboard-container {
  padding: 20px;
}

.dashboard-header {
  margin-bottom: 30px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 10px 0;
}

.page-description {
  font-size: 14px;
  color: #606266;
  margin: 0;
}

.stats-grid {
  margin-bottom: 30px;
}

.stat-card {
  border-radius: 10px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1) !important;
}

.stat-content {
  display: flex;
  align-items: center;
  padding: 20px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
  font-size: 24px;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  line-height: 1;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.charts-row {
  margin-bottom: 30px;
}

.chart-card {
  margin-bottom: 20px;
  border-radius: 10px;
  overflow: hidden;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
  font-size: 16px;
}

.chart-container {
  height: 350px;
  position: relative;
}

.chart-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  border-radius: 4px;
  color: #909399;
}

.chart-placeholder::before {
  content: "图表加载中...";
}

.recent-activity {
  border-radius: 10px;
  overflow: hidden;
}

.activity-list {
  .activity-item {
    display: flex;
    padding: 15px 0;
    border-bottom: 1px solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
    
    .activity-icon {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 15px;
      font-size: 18px;
      flex-shrink: 0;
    }
    
    .activity-content {
      flex: 1;
      
      .activity-title {
        font-size: 15px;
        font-weight: 500;
        color: #303133;
        margin-bottom: 5px;
      }
      
      .activity-description {
        font-size: 13px;
        color: #606266;
        margin-bottom: 5px;
      }
      
      .activity-time {
        font-size: 12px;
        color: #909399;
      }
    }
  }
}

@media (max-width: 768px) {
  .stats-grid {
    .el-col {
      margin-bottom: 15px;
    }
  }
  
  .stat-card {
    .stat-content {
      padding: 15px;
    }
    
    .stat-icon {
      width: 50px;
      height: 50px;
      margin-right: 15px;
      font-size: 20px;
    }
    
    .stat-value {
      font-size: 24px;
    }
  }
  
  .chart-container {
    height: 300px;
  }
}
</style>
